import { useEffect, useRef } from "react";
import { DotLoading } from "antd-mobile";
import HomeHeader from "./components/HomeHeader";
import HomeSwiper from "./components/HomeSwiper";
import HomeLessons from "./components/HomeLessons";
import { useCategory, useSliders, useLessons } from "./hooks";
import { reachBottom, pullRefresh, throttle } from "@/utils";
function Home() {
  const { currentCategory, handleChangeCurrentCategory } = useCategory();
  const { sliders } = useSliders();
  const { lessons, fetchMoreLessons, initLessons } = useLessons();
  const contentRef = useRef<HTMLDivElement>(null);
  // 虚拟列表 1. 定义 HomeLessons ref
  const homeLessonsRef = useRef<() => void>(() => {});
  useEffect(() => {
    if (contentRef.current) {
      reachBottom(contentRef.current, fetchMoreLessons);
      pullRefresh(contentRef.current, initLessons);
      // 虚拟列表 2. 计算 虚拟列表 刷新
      contentRef.current.addEventListener(
        "scroll",
        throttle(homeLessonsRef.current, 16)
      );
      // 从其他页面，返回，页面固定原来位置 2.
      contentRef.current.addEventListener("scroll", () => {
        sessionStorage.setItem(
          "scrollTop",
          contentRef.current!.scrollTop.toString()
        );
      });
    }
  }, []);
  useEffect(() => {
    // 从其他页面，返回，页面固定原来位置 1.
    const scrollTop = sessionStorage.getItem("scrollTop");
    if (scrollTop) {
      contentRef.current!.scrollTop = +scrollTop;
    }
  }, []);
  return (
    <>
      <div className="fixed top-[50px] w-full text-center text-6xl">
        <DotLoading />
      </div>
      <HomeHeader
        currentCategory={currentCategory}
        changeCurrentCategory={handleChangeCurrentCategory}
      />
      {/*  虚拟列表 3. 获取 div dom */}
      <div
        ref={contentRef}
        className="fixed top-10 bottom-10 left-0 w-full overflow-auto bg-white"
      >
        {sliders.length > 0 && <HomeSwiper sliders={sliders} />}
        {/*  虚拟列表 4.  div dom 传给 HomeLessons */}
        <HomeLessons
          ref={homeLessonsRef}
          lessons={lessons}
          fetchMoreLessons={fetchMoreLessons}
          contentRef={contentRef}
        />
      </div>
    </>
  );
}
export default Home;
